package mx.com.matersys.vacs.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import mx.com.matersys.vacs.domain.MapaUrl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Service;

@Service("mySecureResourceFilter")
public class CustomSecureMetadataSource implements FilterInvocationSecurityMetadataSource {
	
	
	static Map<String, Collection<ConfigAttribute>> resourceMap = null;
	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	
	@Autowired
	protected void init() throws Exception{
		loadSourceDefine();
	}

	private void loadSourceDefine() {
		System.out.println("loadSourceDefine INI");
		
		List<MapaUrl> mapaUrls;
		ConfigAttribute confAtt;
		String[] arregloRoles;
		String url;
		String rol;
		Collection<ConfigAttribute> listConfAtt;
		
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		mapaUrls = MapaUrl.findAllMapaUrls();
		
		
		for (MapaUrl mapaUrl : mapaUrls) {
			
			url = mapaUrl.getUrl();
			rol = mapaUrl.getRoles();
			arregloRoles = rol.split(",");
			
			listConfAtt = new ArrayList<ConfigAttribute>();
			
			for (String role : arregloRoles) {
				confAtt = new SecurityConfig(role.trim());
				listConfAtt.add(confAtt);
			}
			
			resourceMap.put(url, listConfAtt);
		}
		System.out.println("loadSourceDefine FIn");
	}
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object filter)
			throws IllegalArgumentException {
		FilterInvocation filterInvocation;
		String urlRequest;
		Iterator<String> ite;
		String urlMapa;
		
		filterInvocation = (FilterInvocation) filter;
		urlRequest = filterInvocation.getRequestUrl();
		System.out.println("url urlRequest: " + urlRequest);

		// obtenemos los roles que cargamos de la base de datos
		ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			urlMapa = ite.next();

			if (urlMatcher.pathMatchesUrl(urlRequest, urlMapa)) {
				return resourceMap.get(urlMapa);
			}
		}
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		System.out.println("getAllConfigAttributes");
		return null;
	}

	@Override
	public boolean supports(Class<?> arg0) {
		System.out.println("supports");
		return true;
	}

}
